let _Vue = null
export default class MyRouter {
    constructor(options) {
        this.options = options
        this.routeMap = {}
        this.data = _Vue.observable({
            current: location.hash.replace('#', '') || '/'
        })
    }
    static install(Vue) {
        // 判断当前插件是否安装
        if (MyRouter.install.installed) return

        MyRouter.install.installed = true
        // 将$router挂在到每一个Vue实例上
        _Vue = Vue
        _Vue.mixin({
            beforeCreate(){
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            },
        })
    }
    init() {
        // 创建路由映射
        this.createRouteMap()
        // 创建 router-view router-link
        this.initComponents()
        // 创建对hash的监听
        this.initEvent()
    }
    createRouteMap() {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        })
    }
    initComponents() {
        _Vue.component('router-link', {
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, [
                    this.$slots.default
                ])
            },
            methods:{
                clickHandler(e) {
                    e.preventDefault()
                    location.hash = this.to
                    this.$router.data.current = this.to
                }
            },
        })

        _Vue.component('router-view', {
            render(h) {
                return h(this.$router.routeMap[this.$router.data.current])
            }
        })
    }
    initEvent() {
        window.onhashchange = () => {
            this.data.current = window.location.hash.replace('#', '')
        }
    }
}